package com.itheima.service.impl;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    //实现接口的方法
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        //调用mapper层的list 从数据库中得到一个dept类型的集合
        List<Dept> deptList = deptMapper.list();
        return deptList;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) {
//        根据ID删除部门
        try {
            deptMapper.deleteById(id);
//            int i =1/0;
//        删除该部门下的所有员工
            empMapper.deleteByDeptId(id);
        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("删除了"+ id +" 部门");
            deptLogService.insert(deptLog);
        }




    }

    @Override
    public void add(Dept dept) {

        deptMapper.jiaru(dept);
    }

    @Override
    public Dept getById(Integer id) {
        Dept dept = deptMapper.getById(id);
        return dept;
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }


}
